import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
    FooterToolbar,
    ModalForm,
    PageContainer,
    ProDescriptions, ProFormCheckbox,
    ProFormText,
    ProFormTextArea,
    ProTable,
    ProFormDateRangePicker, ProFormDigit, ProFormUploadButton,
} from '@ant-design/pro-components';
import {Button, Drawer, Input, message, Modal, Dropdown} from 'antd';
import type {MenuProps} from 'antd';
import React, {useRef, useState} from 'react';
import type {OrganizationListItem} from './data';
import {
    organizationList,
    organizationEdit,
    organizationAdd,
    organizationAddContract,
    organizationSelectList, removeOrganization
} from './service';
import {Link} from "react-router-dom";

const {confirm} = Modal;

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: OrganizationListItem) => {
    const hide = message.loading('正在添加');

    try {
        await organizationAdd({...fields});
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};
/**
 * 更新节点
 *
 * @param fields
 */

export type FormValueType = {
    target?: string;
    template?: string;
    type?: string;
    time?: string;
    frequency?: string;
} & Partial<OrganizationListItem>;


const handleUpdate = async (fields: FormValueType, currentRow?: OrganizationListItem) => {
    const hide = message.loading('正在配置');

    try {
        await organizationEdit({
            ...currentRow,
            ...fields,
        });
        hide();
        message.success('配置成功');
        return true;
    } catch (error) {
        hide();
        message.error('配置失败请重试！');
        return false;
    }
};


const handleAddContract = async (fields: FormValueType, currentRow?: OrganizationListItem) => {
    const hide = message.loading('正在配置');

    try {
        await organizationAddContract({
            "organizationId": currentRow?.organizationId,
            ...fields,
        });
        hide();
        message.success('配置成功');
        return true;
    } catch (error) {
        hide();
        message.error('配置失败请重试！');
        return false;
    }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: OrganizationListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
        await removeOrganization({
            organizationIds: selectedRows.map((row) => row.organizationId),
        });
        hide();
        message.success('删除成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

const items = [
    {
        key: '1',
        label: '1st item',
    },
    {
        key: '2',
        label: '2nd item',
    },
    {
        key: '3',
        label: '3rd item',
    },
];
const onMenuClick: MenuProps['onClick'] = (e) => {
    console.log('click', e);
};

const OrganizationList: React.FC = () => {
    /** 新建窗口的弹窗 */
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    /** 分布更新窗口的弹窗 */
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [addContractModalVisible, handleAddContractVisible] = useState<boolean>(false);
    const [showDetail, setShowDetail] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<OrganizationListItem>();
    const [selectedRowsState, setSelectedRows] = useState<OrganizationListItem[]>([]);

    const [modalTitle, setModalTitle] = useState('');

    /** 国际化配置 */
    const columns: ProColumns<OrganizationListItem>[] = [
        {
            title: '租户',
            dataIndex: "organizationId",
            valueType: 'select',
            search: false,
            hidden: true, // 关闭自动换行
        },
        {
            title: '租户名称',
            dataIndex: 'name',
            search: true,
        },
        {
            title: '合同有效期',
            dataIndex: 'endDate',
            search: false,
        },
        {
            title: '联系人',
            dataIndex: 'contactName',
            valueType: 'text',
            search: false,
        },
        {
            title: '联系人手机号',
            dataIndex: 'contactPhone',
            valueType: 'text',
            search: false,
        },
        {
            title: '余额',
            dataIndex: 'balance',
            valueType: 'text',
            search: false,
            renderText: (val: string) => `￥${val}`,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => {
                let title = `添加合同-${record.name}`;
                var link = `/power/resource-activate/` + record.organizationId
                return [
                    <a
                        key="config"
                        onClick={() => {
                            handleUpdateModalVisible(true);
                            setCurrentRow(record);
                        }}
                    >
                        编辑
                    </a>,
                    <a
                        key="addContract"
                        onClick={() => {
                            handleAddContractVisible(true);
                            setModalTitle(title);
                            setCurrentRow(record);
                        }}
                    >
                        添加合同
                    </a>,
                    <Link to={link}>
                        开通算力
                    </Link>,
                    <Link to={`/organization/resource-manager/`+record.organizationId}>
                        资源管理
                    </Link>,
                ]
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<OrganizationListItem, API.ListPagination>
                headerTitle="租户列表"
                actionRef={actionRef}
                rowKey="organizationId"
                search={{
                    labelWidth: 90,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }}
                    >
                        <PlusOutlined/> 新建
                    </Button>,
                ]}
                request={organizationList}
                columns={columns}
                rowSelection={{
                    onChange: (_, selectedRows) => {
                        setSelectedRows(selectedRows);
                    },
                }}
                options={{
                    density: true,
                    fullScreen: true,
                    reload:true,
                    setting: false
                }}
                expandable={{
                    expandedRowRender: (record) => <span>
              <p style={{marginLeft: 80}}>公司地址：{record.address}</p>
              <p style={{marginLeft: 80}}>公司简介：{record.remark}</p>
          </span>,
                    rowExpandable: (record) => (record.remark !== '' || record.address !== ''),
                }}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a
                                style={{
                                    fontWeight: 600,
                                }}
                            >
                                {selectedRowsState.length}
                            </a>{' '}
                            项 &nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            confirm({
                                title: '删除租户',
                                content: '删除租户前，请确认租户关联主机等资源已清除，账单已结算，是否现在删除?',
                                onOk() {
                                    handleRemove(selectedRowsState);
                                    setSelectedRows([]);
                                    actionRef.current?.reloadAndRest?.();
                                    return true;
                                }
                            });
                        }}
                    >
                        批量删除
                    </Button>
                </FooterToolbar>
            )}

            <ModalForm
                title="添加租户"
                width="550px"
                open={createModalVisible}
                onVisibleChange={handleModalVisible}
                onFinish={async (value) => {
                    const success = await handleAdd(value as OrganizationListItem);
                    if (success) {
                        handleModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                modalProps={{destroyOnClose: true}}
            >
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '租户名称为必填项',
                        },
                    ]}
                    width="md"
                    name="name"
                    label="租户名称"
                />
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '联系人为必填项',
                        },
                    ]}
                    // width="md"
                    name="contactName"
                    label="联系人"
                />
                <ProFormText
                    name="contactPhone"
                    width="md"
                    label="联系人手机号"
                    placeholder="请输入至少11个字符"
                    rules={[
                        {
                            required: true,
                            message: '请输入11位手机号!',
                            len: 11,
                            pattern: /^1\d{10}$/,
                        },
                    ]}
                />
                <ProFormTextArea
                    // width="md"
                    name="address"
                    label="地址"
                />
                <ProFormTextArea

                    // width="md"
                    name="remark"
                    label="租户简介"
                />
            </ModalForm>
            <ModalForm
                title="编辑租户"
                width="550px"
                open={updateModalVisible}
                onVisibleChange={handleUpdateModalVisible}
                onFinish={async (value) => {
                    const success = await handleUpdate(value, currentRow);
                    if (success) {
                        handleUpdateModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                modalProps={{destroyOnClose: true}}
                initialValues={{
                    name: currentRow?.name,
                    contactName: currentRow?.contactName,
                    contactPhone: currentRow?.contactPhone,
                    remark: currentRow?.remark,
                    address: currentRow?.address,
                }}
            >
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '租户名称为必填项',
                        },
                    ]}
                    width="md"
                    name="name"
                    label="租户名称"
                />
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '联系人为必填项',
                        },
                    ]}
                    // width="md"
                    name="contactName"
                    label="联系人"
                />

                <ProFormText
                    name="contactPhone"
                    width="md"
                    label="联系人手机号"
                    placeholder="请输入联系人手机号"
                    rules={[
                        {
                            required: true,
                            message: '请输入正确的手机号!',
                            len: 11,
                            pattern: /^1\d{10}$/,
                        },
                    ]}
                />
                <ProFormTextArea

                    // width="md"
                    name="address"
                    label="地址"
                />
                <ProFormTextArea

                    // width="md"
                    name="remark"
                    label="租户简介"
                />
            </ModalForm>


            <ModalForm
                title={modalTitle}
                width="550px"
                open={addContractModalVisible}
                onVisibleChange={handleAddContractVisible}
                onFinish={async (value) => {
                    const success = await handleAddContract(value, currentRow);
                    if (success) {
                        handleAddContractVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                modalProps={{destroyOnClose: true}}
                initialValues={{
                    name: currentRow?.name,
                }}
            >
                <ProFormText name="organizationId" hidden={true} initialValue={currentRow?.organizationId}/>
                <ProFormDateRangePicker
                    label="起止日期"
                    width="md"
                    name="contractDate"
                    rules={[
                        {
                            required: true,
                            message: '请选择起止日期',
                        },
                    ]}
                    placeholder={['开始日期', '结束日期']}
                />
                <ProFormDigit
                    label="充值金额"
                    name="rechargeAmount"
                    width="md"
                    rules={[
                        {
                            required: true,
                            message: '请输入充值金额',
                        },
                        {
                            pattern: /^(\d+)((?:\.\d+)?)$/,
                            message: '请输入合法金额数字',
                        },
                    ]}
                    placeholder="请输入金额"
                    fieldProps={{
                        prefix: '￥',
                    }}
                />
                <ProFormTextArea
                    // width="md"
                    name="remark"
                    label="合同备注"
                />

            </ModalForm>

        </PageContainer>
    );
};

export default OrganizationList;
